//
//  GFNearFoodViewController.m
//  GoodFood
//
//  Created by dllo on 15/11/5.
//  Copyright © 2015年 荣伟峰. All rights reserved.
//

#import "GFNearFoodViewController.h"

@interface GFNearFoodViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, GFWaterFlowLayoutDelegate,BMKLocationServiceDelegate>

@property (nonatomic, strong) UICollectionView *nearCollectionView;
@property (nonatomic, strong) NSMutableArray *rootArray;
@property (nonatomic, assign) double lat;
@property (nonatomic, assign) double lon;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, strong) BMKLocationService *locService;
@property (nonatomic, copy) NSString *url;

@end

@implementation GFNearFoodViewController

-(void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    [self locServiceData];
    self.locService.delegate = self;
    self.nearCollectionView.footer.hidden = YES;
}

-(void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    self.locService.delegate = nil;
    
}


//定位
-(void)locServiceData {
    
    self.locService = [[BMKLocationService alloc] init];
    [self.locService startUserLocationService];
}


-(void)creatNearCollectionView {
    
    GFWaterFlowLayout *layout = [[GFWaterFlowLayout alloc] init];
    layout.delegate = self;
    
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight - 64) collectionViewLayout:layout];
    collectionView.backgroundColor = [UIColor whiteColor];
    collectionView.dataSource = self;
    collectionView.delegate = self;
    [self.view addSubview:collectionView];
    
    [collectionView registerClass:[GFNearHomeCollectionViewCell class] forCellWithReuseIdentifier:@"near"];
    
    self.nearCollectionView = collectionView;
    
    self.nearCollectionView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh:)];
    self.nearCollectionView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footRefresh:)];
    
}

#pragma mark - 下拉刷新
- (void)headerRefresh:(MJRefreshHeader *)header {
    [self.nearCollectionView.header beginRefreshing];
    self.page = 1;
    [self handleData:self.page];
    [self.nearCollectionView.header endRefreshing];
}
#pragma mark - 上拉加载
- (void)footRefresh:(MJRefreshAutoNormalFooter *)footer {
    //    self.resturtantTableView.footer.hidden = NO;
    [self.nearCollectionView.footer beginRefreshing];
    self.page ++;
    [self handleData:self.page];
    [self.nearCollectionView.footer endRefreshing];
}


-(void)handleData:(NSInteger)page {
    NSLog(@"%f", self.lat);
    self.url = [NSString stringWithFormat:@"http://api.meishixing.com/picture/picturelist/nearby/lng=%f&lat=%f&page=%ld&distance=3000&food_category_name=", self.lon, self.lat, self.page];
    [AFNetHandle GETWithURL:self.url body:nil httpHead:nil responseStyle:JSON success:^(id result) {
       
        NSArray *tempArr = [result objectForKey:@"result"];
        if (self.page == 1) {
            self.rootArray = [NSMutableArray array];
        }
        
        for (NSDictionary *dic in tempArr) {
            GFNearHomeModel *model = [GFNearHomeModel modWithDic:dic];
            [self.rootArray addObject:model];
        }
        
        
        if (tempArr.count != 0) {
            if (self.rootArray.count < 18) {
                self.nearCollectionView.footer.hidden = YES;
            } else {
                self.nearCollectionView.footer.hidden = NO;
            }
        } else {
            self.nearCollectionView.footer.hidden = YES;
        }
        [self.nearCollectionView reloadData];
        [self.waitView removeFromSuperview];
        [self.overTimeView removeFromSuperview];
    } fail:^(NSError *error) {
        [self.overTimeView removeFromSuperview];
        self.overTimeView = [[GFOverTimeView alloc] initWithFrame:self.view.frame withButtonBlock:^(UIButton *button) {
            [self.view addSubview:self.waitView];
            [self handleData:self.page];
        }];
        [self.waitView removeFromSuperview];
        [self.view addSubview:self.overTimeView];
    }];
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.page = 1;
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self creatNearCollectionView];
    [self.view bringSubviewToFront:self.waitView];
    
    
}

#pragma mark - GFWaterFlowLayoutDelegate

-(CGFloat)waterFlowLayout:(GFWaterFlowLayout *)waterFloeLayout heightForWidth:(CGFloat)width atIndexPath:(NSIndexPath *)indexPath {
    
    GFNearHomeModel *model = self.rootArray[indexPath.item];
    
    
    return ([model.image_height floatValue] / 5) / ((ScreenWidth - 15) / 2) * width + ScreenWidth / 15 + 30 + (ScreenWidth - 15) / 6;
    
}

#pragma mark - UICollectionViewDataSource
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.rootArray.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    GFNearHomeModel *model = [self.rootArray objectAtIndex:indexPath.item];
    void(^block)(void) = ^(void) {
        
        GFUserInfoViewController *userInfo = [[GFUserInfoViewController alloc] init];
        userInfo.user_id = model.user_id;
        [self.navigationController pushViewController:userInfo animated:YES];
        
    };
    
    GFNearHomeCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"near" forIndexPath:indexPath];
    cell.model = model;
    cell.block = block;
    return cell;
    
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    GFNearHomeDetialViewController *nearHomeDetialVC = [[GFNearHomeDetialViewController alloc] init];
    nearHomeDetialVC.detialArr = self.rootArray;
    nearHomeDetialVC.url = self.url;
    nearHomeDetialVC.tag = 1;
    nearHomeDetialVC.num = indexPath.item;
    [self.navigationController pushViewController:nearHomeDetialVC animated:YES];
}

-(void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation {
    
    self.lat = userLocation.location.coordinate.latitude;
    self.lon = userLocation.location.coordinate.longitude;
    if (self.lat != 0 && self.lon != 0) {
        [self.locService stopUserLocationService];
    }
    [self handleData:self.page];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
